/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.supplier.modular.structure.position.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.supplier.core.enums.SupplierBuildInEnum;
import vip.xiaonuo.supplier.core.enums.SupplierDataTypeEnum;
import vip.xiaonuo.supplier.modular.structure.org.entity.SupplierOrg;
import vip.xiaonuo.supplier.modular.structure.org.service.SupplierOrgService;
import vip.xiaonuo.supplier.modular.structure.position.entity.SupplierPosition;
import vip.xiaonuo.supplier.modular.structure.position.enums.SupplierPositionCategoryEnum;
import vip.xiaonuo.supplier.modular.structure.position.mapper.SupplierPositionMapper;
import vip.xiaonuo.supplier.modular.structure.position.param.*;
import vip.xiaonuo.supplier.modular.structure.position.service.SupplierPositionService;
import vip.xiaonuo.supplier.modular.structure.user.entity.SupplierUser;
import vip.xiaonuo.supplier.modular.structure.user.service.SupplierUserService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.listener.CommonDataChangeEventCenter;
import vip.xiaonuo.common.page.CommonPageRequest;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 岗位Service接口实现类
 *
 * @author xuyuxiang
 * @date 2022/2/23 18:43
 **/
@Service
public class SupplierPositionServiceImpl extends ServiceImpl<SupplierPositionMapper, SupplierPosition> implements SupplierPositionService {

    @Resource
    private SupplierOrgService supplierOrgService;

    @Resource
    private SupplierUserService supplierUserService;

    @Override
    public Page<SupplierPosition> page(SupplierPositionPageParam supplierPositionPageParam) {
        QueryWrapper<SupplierPosition> queryWrapper = new QueryWrapper<SupplierPosition>().checkSqlInjection();
        // 查询部分字段
        queryWrapper.lambda().select(SupplierPosition::getId, SupplierPosition::getOrgId, SupplierPosition::getName,
                SupplierPosition::getCategory, SupplierPosition::getSortCode);
        if(ObjectUtil.isNotEmpty(supplierPositionPageParam.getOrgId())) {
            queryWrapper.lambda().eq(SupplierPosition::getOrgId, supplierPositionPageParam.getOrgId());
        }
        if(ObjectUtil.isNotEmpty(supplierPositionPageParam.getCategory())) {
            queryWrapper.lambda().eq(SupplierPosition::getCategory, supplierPositionPageParam.getCategory());
        }
        if(ObjectUtil.isNotEmpty(supplierPositionPageParam.getSearchKey())) {
            queryWrapper.lambda().like(SupplierPosition::getName, supplierPositionPageParam.getSearchKey());
        }
        //数据归属
        queryWrapper.lambda().eq(SupplierPosition::getCompanyId, StpLoginUserUtil.getLoginUser().getCompanyId());
        if(ObjectUtil.isAllNotEmpty(supplierPositionPageParam.getSortField(), supplierPositionPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(supplierPositionPageParam.getSortOrder());
            queryWrapper.orderBy(true, supplierPositionPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(supplierPositionPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(SupplierPosition::getSortCode);
        }
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            queryWrapper.lambda().in(SupplierPosition::getOrgId, loginUserDataScope);
        } else {
            return new Page<>();
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(SupplierPositionAddParam supplierPositionAddParam) {
        SupplierPositionCategoryEnum.validate(supplierPositionAddParam.getCategory());
        //如果不是超管，校验数据范围，只能修改下级机构名称
        if(ObjectUtil.notEqual(StpLoginUserUtil.getLoginUser().getAccount(), SupplierBuildInEnum.BUILD_IN_USER_ACCOUNT.getValue())) {
            // 校验数据范围
            List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
            if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
                if (!loginUserDataScope.contains(supplierPositionAddParam.getOrgId())) {
                    throw new CommonException("您没有权限在该机构下增加岗位，机构id：{}", supplierPositionAddParam.getOrgId());
                }
            } else {
                throw new CommonException("您没有权限在该机构下增加岗位，机构id：{}", supplierPositionAddParam.getOrgId());
            }
        }
        SupplierPosition supplierPosition = BeanUtil.toBean(supplierPositionAddParam, SupplierPosition.class);

        boolean repeatName = this.count(new LambdaQueryWrapper<SupplierPosition>().eq(SupplierPosition::getOrgId, supplierPosition.getOrgId())
                .eq(SupplierPosition::getName, supplierPosition.getName())) > 0;
        if(repeatName) {
            throw new CommonException("同机构下存在重复的岗位，名称为：{}", supplierPosition.getName());
        }
        //数据归属
        supplierPosition.setCompanyId(StpLoginUserUtil.getLoginUser().getCompanyId());
        supplierPosition.setCode(RandomUtil.randomString(10));
        this.save(supplierPosition);

        // 发布增加事件
        CommonDataChangeEventCenter.doAddWithData(SupplierDataTypeEnum.POSITION.getValue(), JSONUtil.createArray().put(supplierPosition));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(SupplierPositionEditParam supplierPositionEditParam) {
        SupplierPositionCategoryEnum.validate(supplierPositionEditParam.getCategory());
        SupplierPosition supplierPosition = this.queryEntity(supplierPositionEditParam.getId());
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            if(!loginUserDataScope.contains(supplierPositionEditParam.getOrgId())) {
                throw new CommonException("您没有权限编辑该机构下的岗位，机构id：{}", supplierPositionEditParam.getOrgId());
            }
        } else {
            if(!supplierPositionEditParam.getId().equals(StpUtil.getLoginIdAsString())) {
                throw new CommonException("您没有权限编辑该机构下的岗位，机构id：{}", supplierPositionEditParam.getOrgId());
            }
        }
        BeanUtil.copyProperties(supplierPositionEditParam, supplierPosition);
        boolean repeatName = this.count(new LambdaQueryWrapper<SupplierPosition>().eq(SupplierPosition::getOrgId, supplierPosition.getOrgId())
                .eq(SupplierPosition::getName, supplierPosition.getName()).ne(SupplierPosition::getId, supplierPosition.getId())) > 0;
        if(repeatName) {
            throw new CommonException("同机构下存在重复的岗位，名称为：{}", supplierPosition.getName());
        }
        this.updateById(supplierPosition);

        // 发布更新事件
        CommonDataChangeEventCenter.doUpdateWithData(SupplierDataTypeEnum.POSITION.getValue(), JSONUtil.createArray().put(supplierPosition));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<SupplierPositionIdParam> supplierPositionIdParamList) {
        List<String> positionIdList = CollStreamUtil.toList(supplierPositionIdParamList, SupplierPositionIdParam::getId);
        if(ObjectUtil.isNotEmpty(positionIdList)) {
            // 获取这些岗位的的机构id集合
            Set<String> positionOrgIdList = this.listByIds(positionIdList).stream().map(SupplierPosition::getOrgId).collect(Collectors.toSet());
            // 校验数据范围
            List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
            if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
                if(!loginUserDataScope.containsAll(positionOrgIdList)) {
                    throw new CommonException("您没有权限删除这些机构下的岗位，机构id：{}", positionOrgIdList);
                }
            } else {
                throw new CommonException("您没有权限删除这些机构下的岗位，机构id：{}", positionOrgIdList);
            }
            // 岗位下有人不能删除（直属岗位）
            boolean hasOrgUser = supplierUserService.count(new LambdaQueryWrapper<SupplierUser>().in(SupplierUser::getPositionId, positionIdList)) > 0;
            if(hasOrgUser) {
                throw new CommonException("请先删除岗位下的用户");
            }
            // 岗位下有人不能删除（兼任岗位）
            List<String> positionJsonList = supplierUserService.list(new LambdaQueryWrapper<SupplierUser>()
                    .isNotNull(SupplierUser::getPositionJson)).stream().map(SupplierUser::getPositionJson).collect(Collectors.toList());
            if(ObjectUtil.isNotEmpty(positionJsonList)) {
                List<String> extPositionIdList = CollectionUtil.newArrayList();
                positionJsonList.forEach(positionJson -> JSONUtil.toList(JSONUtil.parseArray(positionJson), JSONObject.class)
                        .forEach(jsonObject -> extPositionIdList.add(jsonObject.getStr("positionId"))));
                boolean hasPositionUser = CollectionUtil.intersectionDistinct(positionIdList, CollectionUtil.removeNull(extPositionIdList)).size() > 0;
                if(hasPositionUser) {
                    throw new CommonException("请先删除岗位下的用户");
                }
            }
            // 执行删除
            this.removeByIds(positionIdList);

            // 发布删除事件
            CommonDataChangeEventCenter.doDeleteWithDataId(SupplierDataTypeEnum.POSITION.getValue(), positionIdList);
        }
    }

    @Override
    public SupplierPosition detail(SupplierPositionIdParam supplierPositionIdParam) {
        return this.queryEntity(supplierPositionIdParam.getId());
    }

    @Override
    public SupplierPosition queryEntity(String id) {
        SupplierPosition supplierPosition = this.getById(id);
        if(ObjectUtil.isEmpty(supplierPosition)) {
            throw new CommonException("岗位不存在，id值为：{}", id);
        }
        return supplierPosition;
    }

    @Override
    public String getPositionIdByPositionNameWithCreate(String orgId, String positionName) {
        return null;
    }

    /* ====岗位部分所需要用到的选择器==== */

    @Override
    public List<Tree<String>> orgTreeSelector() {
        LambdaQueryWrapper<SupplierOrg> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<String> loginUserDataScope = new ArrayList<>();
        StpLoginUserUtil.getLoginUser().getDataScopeList().stream().forEach((dataScope -> {
            loginUserDataScope.addAll(dataScope.getDataScope());
        }));
        // 定义机构集合
        Set<SupplierOrg> supplierOrgSet = CollectionUtil.newHashSet();
        if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
            // 获取所有机构
            List<SupplierOrg> allOrgList = supplierOrgService.list();
            loginUserDataScope.forEach(orgId -> supplierOrgSet.addAll(supplierOrgService.getParentListById(allOrgList, orgId, true)));
            List<String> loginUserDataScopeFullList = supplierOrgSet.stream().map(SupplierOrg::getId).collect(Collectors.toList());
            lambdaQueryWrapper.in(SupplierOrg::getId, loginUserDataScopeFullList);
        } else {
            return CollectionUtil.newArrayList();
        }
        lambdaQueryWrapper.orderByAsc(SupplierOrg::getSortCode);
        List<SupplierOrg> supplierOrgList = supplierOrgService.list(lambdaQueryWrapper);
        List<TreeNode<String>> treeNodeList = supplierOrgList.stream().map(supplierOrg ->
                        new TreeNode<>(supplierOrg.getId(), supplierOrg.getParentId(), supplierOrg.getName(), supplierOrg.getSortCode()))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodeList, "0");
    }

    @Override
    public Page<SupplierPosition> positionSelector(SupplierPositionSelectorPositionParam supplierPositionSelectorPositionParam) {
        LambdaQueryWrapper<SupplierPosition> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            lambdaQueryWrapper.in(SupplierPosition::getOrgId, loginUserDataScope);
        } else {
            return new Page<>();
        }
        // 查询部分字段
        lambdaQueryWrapper.select(SupplierPosition::getId, SupplierPosition::getOrgId, SupplierPosition::getName,
                SupplierPosition::getCategory, SupplierPosition::getSortCode);
        if(ObjectUtil.isNotEmpty(supplierPositionSelectorPositionParam.getOrgId())) {
            lambdaQueryWrapper.eq(SupplierPosition::getOrgId, supplierPositionSelectorPositionParam.getOrgId());
        }
        if(ObjectUtil.isNotEmpty(supplierPositionSelectorPositionParam.getSearchKey())) {
            lambdaQueryWrapper.like(SupplierPosition::getName, supplierPositionSelectorPositionParam.getSearchKey());
        }
        lambdaQueryWrapper.orderByAsc(SupplierPosition::getSortCode);
        return this.page(CommonPageRequest.defaultPage(), lambdaQueryWrapper);
    }
}
